<?php

namespace App\Service;

use App\Contract\ElasticSearch;
use Elasticsearch\ClientBuilder;

class ElkSearch implements ElasticSearch
{
    private $client;

    private $pageNo = 1;

    private $limit = 10;

    public function __construct()
    {
        $hosts = explode(',', env('ELASTICSEARCH_HOST'));
        $this->client = ClientBuilder::create()->setHosts($hosts)->build();
    }

    public function setPageNo(int $pageNo): void
    {
        $this->pageNo = $pageNo;
    }

    public function getPageNo():int
    {
        return $this->pageNo;
    }

    public function setLimit(int $limit): void
    {
        $this->limit = $limit;
    }

    public function getLimit():int
    {
        return $this->limit;
    }

    public function getData(string $index, string $type, $id)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'id' => $id
        ];
        return $this->client->get($params);
    }

    public function search(string $index, string $type, string $field, string $keyword): array
    {
        $params = [
            'index'=> $index,
            'type' => $type,
            'client' => [
                'timeout' => 10,
                'connect_timeout' => 10
            ]
        ];
        $body = [
            'query' => [
                'match' => [
                    $field => $keyword
                ]
            ],
            'sort' => [
                'id' => [
                    'order' => 'asc'
                ]
            ],
            '_source' => [
                'id', 'title', 'createdAt'
            ],
            'from' => ($this->pageNo - 1) * $this->limit,
            'size' => $this->limit
        ];
        $params['body'] = $body;
        return $this->client->search($params);
    }

}